package com.video.Controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.video.entity.Speaker;
import com.video.service.SpeakerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("speaker")
public class SpeakerController {

    @Autowired
    private SpeakerService speakerService;

    @RequestMapping("showSpeakerList")
    public String findAllBySpeaker(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "5") Integer pageSize,
                                   Model model) {

        if(pageNum<1){
            pageNum = 1;
        }else if(pageNum>getTotalPage()){
            pageNum = getTotalPage();
        }

        PageHelper.startPage(pageNum, pageSize);

        List<Speaker> speakers = speakerService.findAll();
        System.out.println(speakers);
        PageInfo<Speaker> speakerPageInfo = new PageInfo<>(speakers);

        model.addAttribute("speakerPageInfo", speakerPageInfo);
        return "/behind/speakerList.jsp";
    }




    public Integer getTotalPage(){
        Integer pageSize = 2;
        Integer totalCount = speakerService.getTotalCount();

        if(totalCount%pageSize == 0){
            return totalCount/pageSize;
        }else {
            return totalCount/pageSize+1;
        }
    }


    @RequestMapping("addSpeaker")
    public String addSpeaker() {
        return "/behind/addSpeaker.jsp";
    }

    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Speaker speaker, Integer id) {

        if (id == null) {
            speakerService.addSpeaker(speaker);
        } else {
            speaker.setId(id);
            speakerService.updateSpeaker(speaker);
        }

        return "redirect:/speaker/showSpeakerList";
    }

    @RequestMapping("speakerDel")
    @ResponseBody
    public String delSpeakerById(Integer id) {
        System.out.println(id);
        Integer count = speakerService.deleteById(id);

        if (count != 0) {

            return "success";
        } else {

            return null;
        }
    }

    @RequestMapping("edit")
    public String edit(Integer id, Model model) {

        System.out.println(id);
        Speaker speaker = speakerService.findById(id);
        model.addAttribute("speaker", speaker);
        return "/behind/addSpeaker.jsp";
    }
}
